<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>数组查找元素位置</title>
	</head>

	<body>
		<h4>题目描述</h4>
		<p>在数组 arr 中，查找值与 item 相等的元素出现的所有位置</p>
		<span>findAllOccurrences('abcdefabc'.split(''), 'a').sort()</span>
		<script type="text/javascript">
			//foreach方法
			function findAllOccurrences1(arr, target) {
				var arr2 = [];
				arr.forEach(function(item, index, arr) {
					if(item == target) {
						arr2.push(index)
					}
				})
				return arr2;
			}
			//for方法 
			function findAllOccurrences2(arr, target) {
				var result = [];
				for(var i = 0; i < arr.length; i++) {
					if(arr[i] == target) {
						result.push(i);
					}
				}
				return result;
			}
			console.log(findAllOccurrences2('abcdefabc'.split(''), 'a'));
			//indexOf
			function findAllOccurrences(arr, target) {
				var res = [];
				index = arr.indexOf(target);
				while(index > -1) {
					res.push(index);
					index = arr.indexOf(target, index + 1);
				}
				return res;
			}
			function findAllOccurrences3(arr, target) {    
		 	var result=[],index=arr.lastIndexOf(target);    
		 	while(index>-1){        
		 		result.push(index);        
		 		arr.splice(index,1);//arr=arr.slice(0,index);        
		 		index=arr.lastIndexOf(target);    
		 		}    
		 		return result;
		 	}
			console.log(findAllOccurrences3('abcdefabc'.split(''), 'a'));
		</script>
	</body>
	 
	 		

</html>